package com.example.SocialApplication.service;

import com.example.SocialApplication.constants.URLs;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.io.InputStream;

public class HttpServices implements URLs{

    public static String callHttpPutRequest(String list, String url) throws IOException {
        String result;

        HttpHost targetHost = new HttpHost(SERVER_ADRESS, SERVER_PORT, "http");

        HttpClient client = new DefaultHttpClient();
        HttpPut put = new HttpPut(url);
        put.addHeader("Content-Type", "application/json");
        put.addHeader("Accept", "application/json");
        put.setEntity(new StringEntity(list));
        HttpResponse response = client.execute(targetHost, put);

        result = getASCIIContentFromEntity(response.getEntity());
        return result;
    }

    public static String callHttpGetRequest(String url) throws IOException {
        String result;

        HttpHost targetHost = new HttpHost(SERVER_ADRESS, SERVER_PORT, "http");

        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(targetHost, httpGet);
        result = getASCIIContentFromEntity(response.getEntity());
        return result;
    }

    private static String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
        InputStream in = entity.getContent();
        StringBuffer out = new StringBuffer();
        int n = 1;
        while (n > 0) {
            byte[] b = new byte[4096];
            n = in.read(b);
            if (n > 0) out.append(new String(b, 0, n));
        }
        return out.toString();
    }
}
